package com.banciyuan.bcywebview.biz.main.mineinfo;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.UserApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.main.discover.topcreator.TopCreatorActivity;
import com.banciyuan.bcywebview.biz.main.mineinfo.sina.SinaFriendsActivity;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sns.SnsUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.Tencent;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.InterestUser;

/**
 * Created by hy on 2016/6/12.
 */
public class AddFriendsActivity extends BaseActivity implements View.OnClickListener {
    private ListView mListView;
    private LayoutInflater mLayoutInflater;
    private RequestQueue mQueue;
    private List<InterestUser> mInterestUsers;
    private ProgressbarHelper mProgressbarHelper;
    private Tencent mTencent;
    private IWXAPI mWxApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addfriends_layout);
        initArgs();
        initProgressbar();
        initActionbar();
        initUi();
        initAction();
        initData();
    }

    @Override
    protected void initArgs() {
        mLayoutInflater = LayoutInflater.from(this);
        mQueue = VolleyQueue.getRquest(this);
        mTencent = Tencent.createInstance(MyConstants.QQ_LOGIN_APP_ID, getApplicationContext());
        mWxApi = WXAPIFactory.createWXAPI(this, MyConstants.WEIXIN_APP_ID, true);
        mWxApi.registerApp(MyConstants.WEIXIN_APP_ID);
    }

    @Override
    protected void initProgressbar() {
        View mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initActionbar() {
        View mActionBarView = findViewById(R.id.base_action_bar);
        ActionbarHelper mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.add_friends));
    }

    @Override
    protected void initUi() {
        mListView = (ListView) findViewById(R.id.lv);
        View header = mLayoutInflater.inflate(R.layout.add_friends_header, mListView, false);
        View footer = mLayoutInflater.inflate(R.layout.add_friends_footer, mListView, false);
        header.findViewById(R.id.view_weibo_friends).setOnClickListener(this);
        header.findViewById(R.id.view_weichat_friends).setOnClickListener(this);
        header.findViewById(R.id.view_qq_friends).setOnClickListener(this);
        footer.findViewById(R.id.tv_top_creator).setOnClickListener(this);
        mListView.addHeaderView(header);
        mListView.addFooterView(footer);
    }

    @Override
    protected void initAction() {
    }

    @Override
    protected void initData() {
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + UserApi.getInterestUser();
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject result = new JSONObject(s);
                    if (StatusCodeUtils.dealStatusCode(s, AddFriendsActivity.this)) {
                        Gson gson = new Gson();
                        mInterestUsers = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<InterestUser>>() {
                        }.getType());
                        popIllegalData();
                        processData();
                    } else {
                        mProgressbarHelper.onFailed();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mProgressbarHelper.onFailed();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, this, params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
    }

    private void popIllegalData() {
        for (InterestUser interestUser : mInterestUsers) {
            List<InterestUser.UserPost> illeglData = new ArrayList<>();
            for (int i = 0; i < interestUser.getPosts().size(); i++) {
                String type = interestUser.getPosts().get(i).getPost_type();
                if (!"cos".equals(type) && !"illust".equals(type) && !"novel".equals(type))
                    illeglData.add(interestUser.getPosts().get(i));
            }
            interestUser.getPosts().removeAll(illeglData);
        }
    }

    private void processData() {
        mListView.setAdapter(new AddFriendsAdapter(this, mInterestUsers, mListView));
        mProgressbarHelper.onSuccess();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.view_weibo_friends:
                gotoUtil.gotoAct(this, SinaFriendsActivity.class);
                break;
            case R.id.view_weichat_friends:
                if (mWxApi.isWXAppInstalled()) {
                    SnsUtil.share2Weixin(this, getShareMap(), mWxApi);
                } else {
                    MyToast.show(this, getString(R.string.weixin_notinstalled));
                }
                break;
            case R.id.view_qq_friends:
                SnsUtil.share2QQ(this, getShareMap(), mTencent);
                break;
            case R.id.tv_top_creator:
                gotoUtil.gotoAct(this, TopCreatorActivity.class);
                break;
        }
    }

    private Map<String, String> getShareMap() {
        return SnsUtil.parseTimeLine(this, getString(R.string.app_load_address), "",
                String.format(getString(R.string.add_friends_share_content), UserDataHelper.getInstance(this).getUname()), getString(R.string.add_friends_share_title));
    }
}